//
//  AppDelegate.m
//  Fangmm
//
//  Created by 阮琦 on 16/1/28.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "AppDelegate.h"
#import "MainIndexViewController.h"
#import "MenuViewController.h"
#import "HouseDetailViewController.h"
#import "PersonCentreViewController.h"
#import "MainNavigationViewController.h"
#import "RentalDemandViewController.h"
#import "ChooseLoginModeViewController.h"
#import "MobileLoginViewController.h"
#import "PreNavigationViewController.h"
#import "NewRequirementViewController.h"
#import "MessageViewController.h"
#import "WebViewController.h"

#import "DropShadowView.h"
#import "AppDrawer.h"
#import "Utility.h"
#import "Constants.h"
#import "User.h"
#import "HttpServer.h"
#import "Requirement.h"

#import "WXApi.h"
#import "ACMacros.h"
#import "JPUSHService.h"

#import <TSMessages/TSMessageView.h>
#import "UserGuideViewController.h"
#import <MobClick.h>

@interface AppDelegate () <WXApiDelegate,UserGuideViewControllerDelegate>
{
    PreNavigationViewController *preNavigationVC;

}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [Utility setObject:@"false" key:kCanBeLandScape];
    [WXApi registerApp:@"wx6fb1728f4cd25c6e"];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick startWithAppkey:@"5703282767e58e4be4001789" reportPolicy:BATCH channelId:nil];
    [MobClick setEncryptEnabled:YES];
    [self getOpenArea];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:@{} appKey:kJPushKey channel:@"app_store" apsForProduction:false];
    NSString *token = [Utility getObjectForKey:kToken];
    if (token == nil || [token isEqual:@""] || [token isEqual:kToken]) {
        ChooseLoginModeViewController *chooseLoginModelVC = [[ChooseLoginModeViewController alloc]initWithNibName:@"ChooseLoginModeViewController" bundle:nil];
        preNavigationVC = [[PreNavigationViewController alloc]initWithRootViewController:chooseLoginModelVC];
    } else {
//        if ([Utility getObjectForKey:kRequirement] == nil) {
//            NewRequirementViewController *newRequirementVC = [[NewRequirementViewController alloc]initWithNibName:@"NewRequirementViewController" bundle:nil];
//            preNavigationVC = [[PreNavigationViewController alloc]initWithRootViewController:newRequirementVC];
//        } else {
            preNavigationVC = [[PreNavigationViewController alloc]initWithRootViewController:[AppDrawer sharedDrawer]];
//        }
    }
    //判断是不是第一次启动应用
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"第一次启动");
        //如果是第一次启动的话,使用UserGuideViewController (用户引导页面) 作为根视图
        UserGuideViewController *userGuideViewController = [[UserGuideViewController alloc] init];
        userGuideViewController.delegate = self;
        self.window.rootViewController = userGuideViewController;
    }
    else
    {
        NSLog(@"不是第一次启动");
        self.window.rootViewController = preNavigationVC;
        //如果不是第一次启动的话,使用LoginViewController作为根视图
    }
    User *user = [User sharedUser];
    user = [Utility getObjectForKey:kUser];
    //Umeng
    [MobClick profileSignInWithPUID:kUserId];
    [self getAccountMsg];
    [self.window makeKeyAndVisible];
    [NSThread sleepForTimeInterval:3.0];
    return YES;
}
//点击引导页面点击进入程序
-(void)popToRootViewController
{
    self.window.rootViewController = preNavigationVC;
}

-(void)getAccountMsg
{
    [HttpServer getAccountMssageWithSuccessBlock:^(NSDictionary *responseData)
    {
        NSLog(@"账户输出＝＝=%@",responseData);
        NSDictionary *resourceDic = responseData[@"account"];
        [Utility setObject:[NSString stringWithFormat:@"%d",[resourceDic[@"balance"] intValue]/100] key:kBalance];
        [Utility setObject:[NSString stringWithFormat:@"%d",[resourceDic[@"trusteeFee"] intValue]/100] key:kTrusteeFee];
    }
    withFailBlock:^(id errorMsg)
    {
        NSLog(@"账户输出ERROR:%@",errorMsg);
    }];
}
- (void)getOpenArea {
    [HttpServer getOpenAreaWithSuccessBlock:^(NSDictionary *openAreaData) {

        id regions = [openAreaData objectForKey:@"city"];
        NSString *regionCode = [NSString stringWithFormat:@"%@",[regions objectForKey:@"code"]];
        if (regionCode == nil || [regionCode isEqualToString:@""]) {
            regionCode = @"3502";
        }
        [Utility setObject:regionCode key:kCityCode];
        [Utility setObject:regions key:kOpenArea];
    } withFailBlock:^(id failData)
    {
        NSLog(@"%@",failData);
    }];

}

- (void)getRequirement {
    [HttpServer getUserRequirementsWithSuccessBlock:^(NSDictionary *successDic) {
        Requirement *requirement = [[Requirement alloc]initWithDic:[successDic objectForKey:@"requirement"]];
        [Utility setObject:requirement key:kRequirement];
        [HttpServer getRequirementsStatistics:requirement WithSuccessBlock:^(NSDictionary *successDic) {
        } withFailBlock:^(id failData) {
            
        }];
    } withFailBlock:^(id failData) {
        
    }];

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:self];
}


- (void)onResp:(BaseResp *)resp {
    // 向微信请求授权后,得到响应结果
    PreNavigationViewController *preNav = (PreNavigationViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *temp = (SendAuthResp *)resp;
        NSLog(@"%@",temp.code);
        [HttpServer getWXcodeWithCode:temp.code WithSuccessBlock:^(NSDictionary *successDic) {
            if ([[successDic allKeys]containsObject:@"openid"] && [[successDic allKeys]containsObject:@"access_token"]) {
                [HttpServer getWXUserWithOpenId:[successDic objectForKey:kWXOpenId] andAccessToken:[successDic objectForKey:kWXAccessToken] WithSuccessBlock:^(NSDictionary *successData) {
                    if ([[successData allKeys]containsObject:@"openid"]) {
                        [HttpServer postToAuthLoginWithOpenId:[successDic objectForKey:kWXOpenId] andAccessToken:[successDic objectForKey:kWXAccessToken] WithWechatUserData:successData WithSuccessBlock:^(NSDictionary *successLoginDic) {
                            if ([[successLoginDic allKeys]containsObject:@"user"]) {
                                [[User sharedUser] setValuesForKeysWithDictionary:[successLoginDic objectForKey:@"user"]];
                                User *user = [User sharedUser];
                                [Utility setObject:user key:kUser];
                                [Utility setObject:[successLoginDic objectForKey:@"token"] key:kToken];
                                [Utility setObject:user.userId key:kUserId];
                                [JPUSHService setAlias:[User sharedUser].userId callbackSelector:nil object:nil];
                                if ([[successLoginDic allKeys]containsObject:@"requirement"]) {
                                    Requirement *requirement = [[Requirement alloc]initWithDic:[successLoginDic objectForKey:@"requirement"]];
                                    [Utility setObject:requirement key:kRequirement];
                                }
                                [[AppDrawer sharedDrawer]removeFromParentViewController];
                                [preNav presentViewController:[AppDrawer rebuildDrawer] animated:true completion:^{
                                    UINavigationController *nav = (UINavigationController *)[AppDrawer sharedDrawer].centerViewController;
                                    [nav popToRootViewControllerAnimated:true];
                                }];
//                                else {
//                                    NewRequirementViewController *newRequirementVC = [[NewRequirementViewController alloc]initWithNibName:@"NewRequirementViewController" bundle:nil];
//                                    [preNavigationVC presentViewController:newRequirementVC animated:true completion:^{
//                                    }];
//                                }
                            } else {
                                MobileLoginViewController *mobileLoginVC = [[MobileLoginViewController alloc]initWithNibName:@"MobileLoginViewController" bundle:nil];
                                mobileLoginVC.oauthId = [successLoginDic objectForKey:@"oauthId"];
                                [preNavigationVC pushViewController:mobileLoginVC animated:true];
                            }
                        } withFailBlock:^(id failData) {
                            [TSMessage showNotificationInViewController:preNavigationVC title:@"授权失败!" subtitle:@"请稍后重试登录" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
                            NSLog(@"%@",failData);
                        }];
                    }
                } withFailBlock:^(id failData) {
                    NSLog(@"%@",failData);
                }];
            }
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    } else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        if (resp.errCode == 0) {
            [TSMessage showNotificationInViewController:[AppDrawer sharedDrawer] title:@"分享成功!" subtitle:@"" type:TSMessageNotificationTypeSuccess duration:2.0 canBeDismissedByUser:true];
        }
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    [JPUSHService setAlias:[User sharedUser].userId callbackSelector:nil object:nil];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:[UIApplication sharedApplication].applicationIconBadgeNumber + 1];
//服务端中Extras字段，key是自己定义的
    if ([[userInfo objectForKey:@"type"] isEqualToString:@"recommend"]) {
        NSMutableArray *recommendArray = [[NSMutableArray alloc]init];
        if ([Utility getObjectForKey:kRecommendArray] == nil) {
        } else {
            recommendArray = [Utility getObjectForKey:kRecommendArray];
        }
        [recommendArray addObject:userInfo];
        [Utility setObject:recommendArray key:kRecommendArray];
    } else {
        NSMutableArray *messageArray = [[NSMutableArray alloc]init];
        if ([Utility getObjectForKey:kMessageArray] == nil) {
        } else {
            messageArray = [Utility getObjectForKey:kMessageArray];
        }
        [messageArray addObject:userInfo];
        [Utility setObject:messageArray key:kMessageArray];
        MainNavigationViewController *mainNav = (MainNavigationViewController *)[AppDrawer sharedDrawer].centerViewController;
        MessageViewController *messageVC = [[MessageViewController alloc]init];
        [mainNav pushViewController:messageVC animated:true];
    }
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSString *canbeLandScape = [Utility getObjectForKey:kCanBeLandScape];
    if (![canbeLandScape isEqual:@"false"]) {
//        [Utility setObject:@"false" key:kCanBeLandScape];
        return UIInterfaceOrientationMaskLandscape;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [JPUSHService setBadge:0];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
